﻿using System;
using NUnit.Core;
using SeleniumToolkit.Core;

namespace SeleniumToolkit.NUnit
{
    /// <summary>
    /// Represents a TestFixture marked with a [WebFixture] attribute.
    /// </summary>
    internal class SeleniumTestFixture : NUnitTestFixture, ISessionInfo
    {
        public SeleniumTestFixture(Type fixtureType)
            : base(fixtureType)
        {
        }

        /// <summary>
        /// overloaded constructor
        /// </summary>
        /// <param name="fixtureType">.NET Type of the hosted test fixture</param>
        /// <param name="browserString">selenium browser profile</param>
        /// <param name="baseUrl">base url for the fixture</param>
        /// <param name="timeout">request timeout for the selenium browser</param>
        /// <param name="sessionOwner">flag to indicate whether the fixture owns the selenium browser startup and shutdown lifecycle</param>
        public SeleniumTestFixture(Type fixtureType, string browserString, string baseUrl, int timeout, bool sessionOwner) : base(fixtureType) 
        {
            DefaultBrowser = browserString;
            BaseUrl = baseUrl;
            Timeout = timeout.ToString();
            SessionOwner = sessionOwner;
        }

        protected override void DoOneTimeSetUp(TestResult suiteResult)
        {
            try
            {
                _browser = new Browser(this);
                base.DoOneTimeSetUp(suiteResult);
            }
            catch (Exception ex)
            {
                suiteResult.Error(ex, FailureSite.SetUp);
            }
        }

        protected override void DoOneTimeTearDown(TestResult suiteResult)
        {
            try
            {
                base.DoOneTimeTearDown(suiteResult);

                _browser.Dispose();
            }
            catch (Exception ex)
            {
                suiteResult.Error(ex, FailureSite.TearDown);
            }
        }

        private Browser _browser;


        #region ISessionInfo Members

        public string Timeout
        {
            get;
            set;
        }

        public string DefaultBrowser
        {
            get;
            set;
        }

        public string BaseUrl
        {
            get;
            set;
        }

        public bool SessionOwner
        {
            get;
            set;
        }

        #endregion
    }
}
